package cn.com.infcn.monitor.web;

import cn.com.infcn.monitor.util.IFCWebUtils;

public class RequestContext implements Cloneable{
	private final String requestName;
	private final String completeRequestName;
	private final String remoteUser;
	private final long threadId;
	private final long startTime;
	private final long startCpuTime;
	
	public RequestContext(String requestName, String completeRequestName, String remoteUser, long startCpuTime) {
		this(requestName, completeRequestName, remoteUser, Thread
				.currentThread().getId(), System.currentTimeMillis(), startCpuTime);
	}

	public RequestContext(String requestName, String completeRequestName, String remoteUser, long threadId,
			long startTime, long startCpuTime) {
		super();
		assert requestName != null;
		assert completeRequestName != null;
		this.requestName = requestName;
		this.completeRequestName = completeRequestName;
		this.remoteUser = remoteUser;
		this.threadId = threadId;
		this.startTime = startTime;
		this.startCpuTime = startCpuTime;
	}
	
	public String getRequestName() {
		return requestName;
	}

	public String getCompleteRequestName() {
		return completeRequestName;
	}

	public String getRemoteUser() {
		return remoteUser;
	}

	public long getThreadId() {
		return threadId;
	}
	
	/**
	 * 获取该方法执行时间
	 * @param timeOfSnapshot
	 * @return
	 */
	public int getDuration(long timeOfSnapshot) {
		return (int) Math.max(timeOfSnapshot - startTime, 0);
	}
	
	public int getCpuTime() {
		if (startCpuTime < 0) {
			return -1;
		}
		final int cpuTime = (int) (IFCWebUtils.getCurrentThreadCpuTime() - startCpuTime) / 1000000;
		return Math.max(cpuTime, 0);
	}

	@Override
	protected RequestContext clone(){
		final RequestContext clone = new RequestContext(getRequestName(), getCompleteRequestName(), getRemoteUser(), getThreadId(),
				startTime, startCpuTime);
		return clone;
	}
	
	
}
